package com.example.hr.text_android;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.hr.text_android.adapter.FabuAdapter;
import com.example.hr.text_android.adapter.GridPictureAdapter;
import com.example.hr.text_android.entity.BookEntity;
import com.example.hr.text_android.entity.Main3Model;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DebugUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by hr on 2017/7/31.
 */
public class Main3Activity extends FragmentActivity implements BaseQuickAdapter.OnItemClickListener, View.OnClickListener, View.OnKeyListener {
    private RecyclerView recycleView;
    private List<Main3Model> list;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int themeId;
    //    private FabuAdapter adapter;
    private GridPictureAdapter adapter;
    private Button bt;
    private EditText edit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        initView();
        initData();
        initAdapter();
    }

    private void initAdapter() {
//        adapter = new FabuAdapter(getApplicationContext());
//        adapter.setList(selectList);
//        adapter.setOnItemClickListener(this);
//        recycleView.setAdapter(adapter);
        adapter = new GridPictureAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        recycleView.setAdapter(adapter);
    }

    private void initData() {
        list = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            Main3Model main3Model = new Main3Model();
            main3Model.setImageResource(R.mipmap.ic_addpic);
            main3Model.setPath("/storage/emulated/0/PictureSelector/CameraImage/PictureSelector_20170802_170230.JPEG");
            list.add(main3Model);
        }

    }

    private void initView() {
        themeId = R.style.picture_default_style;
        recycleView = (RecyclerView) findViewById(R.id.main3_recycle_view);
        bt = (Button) findViewById(R.id.send_btn);
        bt.setOnClickListener(this);
        //edittext 点击@人 一键删除@人
        edit = (EditText) findViewById(R.id.content_et);
        edit.setOnKeyListener(this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recycleView.setLayoutManager(gridLayoutManager);

    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//        PhotoPickerIntent intent = new PhotoPickerIntent(MainActivity.this);
//        intent.setSelectModel(SelectModel.MULTI);
//        intent.setShowCarema(true); // 是否显示拍照
//        intent.setMaxTotal(6); // 最多选择照片数量，默认为6
//        intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
//        startActivityForResult(intent, REQUEST_CAMERA_CODE);

        Toast.makeText(this, "点击了我" + position, Toast.LENGTH_LONG).show();
        PictureSelector.create(Main3Activity.this)
                .openGallery(PictureMimeType.ofAll())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .theme(themeId)
                .previewImage(false)// 是否可预览图片
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    private GridPictureAdapter.OnAddPicClickListener onAddPicClickListener = new GridPictureAdapter.OnAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            Toast.makeText(getApplicationContext(), "点击了我", Toast.LENGTH_LONG).show();
            PictureSelector.create(Main3Activity.this)
                    .openGallery(PictureMimeType.ofAll())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                    .theme(themeId)
                    .previewImage(false)// 是否可预览图片
                    .selectionMedia(selectList)// 是否传入已选图片
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    DebugUtil.i("000", "onActivityResult:" + selectList.size());
                    break;
            }
        }
    }

    /**
     * 获取图片的地址
     */
    private void picPath() {
        for (int i = 0; i < selectList.size(); i++) {
            LocalMedia localMedia = selectList.get(i);
            String path = localMedia.getPath();
            Log.d("zzz", i + "picPath: " + path);
        }
    }

    private ArrayList<BookEntity> mList = new ArrayList<BookEntity>();

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_btn:
                picPath();
                int nextInt = new Random().nextInt(100);
                String str = "#测试测试" + nextInt + "# ";
                edit.setText(edit.getText());
                edit.append(str);
                edit.setSelection(edit.getText().toString().length());
                mList.add(new BookEntity(str, nextInt));
                break;
        }
    }

    /**
     * 监听删除按键，执行删除动作
     *
     * @param view
     * @return
     */
    @Override
    public boolean onKey(View view, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DEL &&
                event.getAction() == KeyEvent.ACTION_DOWN) { //当为删除键并且是按下动作时执行
            int selectionStart = edit.getSelectionStart();
            int lastPos = 0;
            for (int i = 0; i < mList.size(); i++) { //循环遍历整个输入框的所有字符
                if ((lastPos = edit.getText().toString().indexOf(mList.get(i).getBookName(), lastPos)) != -1) {
                    if (selectionStart != 0 && selectionStart >= lastPos &&
                            selectionStart <= (lastPos + mList.get(i).getBookName().length())) {
                        String sss = edit.getText().toString();
                        edit.setText(sss.substring(0, lastPos) +
                                sss.substring(lastPos + mList.get(i).getBookName().length())); //字符串替换，删掉符合条件的字符串
                        mList.remove(i); //删除对应实体
                        edit.setSelection(lastPos); //设置光标位置
                        return true;
                    }
                } else {
                    lastPos += ("#" + mList.get(i).getBookName() + "#").length();
                }
            }
        }
        return false;

    }
}
